package com.loop.netty.protocoltcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;

/**
 * @author zhangxiaolu
 * @since 2023-09-23 22:44
 */
public class MyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        // 接收回送的消息
        int len = msg.getLen();
        byte[] content = msg.getContent();
        String message = new String(content, StandardCharsets.UTF_8);
        System.out.println("客户端接收的消息长度：" + len);
        System.out.println("内容：" + message);
        System.out.println("服务器接收到消息的数量  = " + (++this.count));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 使用客户端发送十条数据
        for (int i = 0; i < 5; i++) {
            String message = "今天吃烧烤了";
            byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
            int length = bytes.length;

            // 创建协议包对象
            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setLen(length);
            messageProtocol.setContent(bytes);
            ctx.writeAndFlush(messageProtocol);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
